import 'package:flutter/cupertino.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';

class ConnectivityDemo extends StatefulWidget {
  @override
  _ConnectivityDemoState createState() => _ConnectivityDemoState();
}

class _ConnectivityDemoState extends State<ConnectivityDemo> {
  String _state = "没有网络";
  var _subscription;
  @override
  initState() {
    super.initState();
    this._createNet();
  }

  _createNet() {
    print('init ConnectivityDemo');
    _subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      print('init ConnectivityDemo $result');
      if (result == ConnectivityResult.mobile) {
        setState(() {
          _state = "手机网络";
        });
      } else if (result == ConnectivityResult.wifi) {
        setState(() {
          _state = "Wifi 网络";
        });
      } else {
        setState(() {
          _state = "没有网络";
        });
      }
    });
  }

  @override
  dispose() {
    super.dispose();
    this._createNet();
    _subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("检测网络变化"),
      ),
      body: Text("${this._state}"),
    );
  }
}
